package com.ykdl.member.kid.regandlogin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oauth.signpost.http.HttpParameters;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import net.wxxr.http.util.Sig;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.google.gdata.util.common.base.Escaper;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.CardAdapter;
import com.ykdl.member.kid.beans.ResetPasswordBean;
import com.ykdl.member.kid.beans.ResultBean;
import com.ykdl.member.kid.beans.StoreBean;
import com.ykdl.member.kid.beans.StoreInfoJsonBean;
import com.ykdl.member.kid.beans.Store_ListBean;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.gears.HomeActivity;
import com.ykdl.member.kid.regandlogin.ForgetPwActivity.resetpasswordTag;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class ChoooseCardActivity extends BaseScreen implements OnClickListener{
	private Dialog builder = null;
	private RefreshListView lv = null;
	private CardAdapter adapter  = null;
    private View viewDialog ;
    private TextView store_name;
    private String favorite_store="" ;
    private String placeString="" ;
    private RelativeLayout lr ; 
    private TextView notice ;
    private Boolean isHasCard=true ;
    private int start_id = 0;
	private int cursor = 0;
	private int count = 20;
	private boolean issetleftlist = false;
	private ArrayList<StoreInfoJsonBean> store_list = new ArrayList<StoreInfoJsonBean>();
	private String NowState="";
	private String babybirthday="";
	private String gender_baby="";
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTopTitle("门店选择", 0, R.drawable.back_bg, new OnClickListener() {
			@Override
			public void onClick(View v) {

				finish();
			}
		}, R.string.turn_ok, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
//				if (isHasCard) {
					addCard();
//				}else {
//					go(HomeActivity.class);
//					ResoureUtil.exit();
//					ChoooseCardActivity.this.finish();
//				}
				
			}
		}, R.drawable.title_bg, false);
		placeString = this.getIntent().getStringExtra(KidAction.PLACE_STRING);
		NowState= this.getIntent().getStringExtra("COMEFROM1"); //状态
		babybirthday=this.getIntent().getStringExtra("birthday");
		gender_baby=this.getIntent().getStringExtra("gender");
		setContent(R.layout.chooosecardactivity_xml);
		ResoureUtil.activityList.add(this);
		inint();
		getData();
	}
	public void inint() {
		issetleftlist=true;
		lr = (RelativeLayout)findViewById(R.id.lr);
		notice = (TextView)findViewById(R.id.notice);
		builder = new Dialog(this);
		builder.setTitle("选择门店");
		LayoutInflater inflater = LayoutInflater.from(this);
		viewDialog = inflater.inflate(R.layout.dialog, null);
		Display display = this.getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		//设置对话框的宽高
		LayoutParams layoutParams = new LayoutParams(width * 90 / 100,
				LayoutParams.WRAP_CONTENT);
		builder.setContentView(viewDialog, layoutParams);
		store_name  = (TextView)findViewById(R.id.store_name);
		findViewById(R.id.store_name).setOnClickListener(this);
		adapter = new CardAdapter(ChoooseCardActivity.this);
		lv = (RefreshListView) viewDialog.findViewById(R.id.lv_remain_item);
		lv.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				store_list = new ArrayList<StoreInfoJsonBean>();
				issetleftlist=false;
				count = 20;
				cursor = 0;
				getData();
			}
		});
		lv.setMoreClick(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				issetleftlist=false;
				count = 20;
				getData();
			}
		});
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				StoreInfoJsonBean bean = (StoreInfoJsonBean)adapter.getItem(position);
				store_name.setTextColor(Color.BLACK);
				store_name.setText(bean.getName());
				favorite_store = bean.getStore_id();
				builder.dismiss();
			}

		});
	}
	public void getData() {
		if (issetleftlist) {
			showProgress("正在发送请稍等...");	
		}
		String  pageurl = KidConfig.GET_STOR_LIST;
		Map<String,String> map = new HashMap<String, String>();
		Sig sig=new Sig();
		String sigstr = sig.getSig(map);
		HttpParameters parameterss = new HttpParameters();
//		parameterss.put("sig", "65b37a2a7dba87d27cbc4017ab3957dc");
		String area="";
		try {
			area = URLEncoder.encode(placeString, "utf8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		parameterss.put("area", area);
		parameterss.put("start_id", String.valueOf(start_id));
		parameterss.put("cursor", String.valueOf(cursor));
		parameterss.put("count", String.valueOf(count));
		HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl, parameterss, null);
		 TaskManager.startHttpRequest(request, new getDataTag(),  Store_ListBean.class);
		
	}
	class getDataTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof Store_ListBean) {
				finishProgress();
				Store_ListBean bean = (Store_ListBean)t;
				if (bean.getStores()!=null) {
					if (bean.getStores().size()>0) {
						notice.setVisibility(View.GONE); 
						int index = 0;
						if (store_list.size() > 1) {
							index = store_list.size() - 1;
						}
							for (StoreInfoJsonBean obj : bean.getStores()) {
								store_list.add(obj);
							}
							adapter.setlist(store_list);
							lv.setAdapter(adapter);
							lr.setVisibility(View.VISIBLE);
							adapter.notifyDataSetChanged();
							if (bean.getNext_cursor() == bean.getTotal_number()) {
								lv.setMoreButtoIsGon(true);
							} else {
								cursor = bean.getNext_cursor(); 
								lv.setMoreButtoIsGon(false);
							}
							if (!issetleftlist) {
								lv.setSelection(index);
							}
							isHasCard = true;
					}else {
						isHasCard = false;
						lr.setVisibility(View.GONE);
						notice.setVisibility(View.VISIBLE);
					}
					
					
				}else {
					isHasCard = false;
					lr.setVisibility(View.GONE);
					notice.setVisibility(View.VISIBLE);
				}
				
				lv.onRefreshComplete();
				lv.setFecthMoreOk();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "参数有误失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	public void addCard() {
		String  pageurl = KidConfig.CHANGE_PROFILE;
		HttpParameters bodyParams = new HttpParameters();
		if (isHasCard) {
			if(favorite_store.equals("")){
				Toast.makeText(mContext, "请选择门店", 1).show();
				return;
			}
			bodyParams.put("favorite_store", favorite_store);
		}
		    showProgress("正在发送请稍等...");
			bodyParams.put("favorite_store", favorite_store);
			if(NowState.equals("yunqi")){
				bodyParams.put("due_date", babybirthday);
				bodyParams.put("status", String.valueOf(1));
			}else if(NowState.equals("baby")){
				bodyParams.put("gender", gender_baby);
				bodyParams.put("birthday", babybirthday);
				bodyParams.put("status", String.valueOf(2));
			}else{
				bodyParams.put("user_birthday", babybirthday);
				bodyParams.put("status", String.valueOf(3));
			}
			try {
				placeString = URLEncoder.encode(placeString, "utf8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			bodyParams.put("address", placeString);
			HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl, bodyParams, null);
			 TaskManager.startHttpRequest(request, new addCardTag(),  ResultBean.class);
		
	}
	class addCardTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof ResultBean) {
				finishProgress();
				ResultBean bean = (ResultBean)t;
				if (null==bean.getError()) {
					Toast.makeText(mContext, "成功", 1).show();
					go(HomeActivity.class);
					ResoureUtil.exit();
					ChoooseCardActivity.this.finish();
				}else {
					Toast.makeText(mContext, "失败,"+bean.getDesc(), 1).show();
					go(HomeActivity.class);
					ResoureUtil.exit();
					ChoooseCardActivity.this.finish();
				}
				Log.e("ChoooseCardActivity", "选门店：bean.getError()="+bean.getError());
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			go(HomeActivity.class);
			ResoureUtil.exit();
//			Toast.makeText(mContext, "参数有误失败", 1).show();
			Log.e("ChoooseCardActivity", "选门店： refreshError");
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	/** 显示对话框 **/
	public void showDialog() {
		builder.show();
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.store_name:
			showDialog() ;
			break;
		}
	}
}
